import { Button, Form, Input } from 'antd';
import { LoginParams } from '@/api/services/userServices.ts';
import { useLogin } from '@/store/userStore.ts';
import { useState } from 'react';
import { md5 } from 'js-md5';
import { useLocation } from 'react-router-dom';

const LoginForm = () => {
  const [form] = Form.useForm<LoginParams>();
  const login = useLogin();
  const [loading, setLoading] = useState(false);
  const { search } = useLocation();
  const path = new URLSearchParams(search).get('redirect');

  const handleLogin = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    try {
      setLoading(true);
      await login({ userName: values.userName, password: md5(values.password) }, path);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form form={form} layout={'vertical'} className="pt-32" onFinish={handleLogin}>
      <Form.Item
        name="userName"
        label={<div className="text-level-3-l">账号</div>}
        className="mb-10"
        rules={[{ required: true, message: '请输入您的登录账号' }]}
      >
        <Input className="px-4 py-3" placeholder="请输入您的登录账号" />
      </Form.Item>
      <Form.Item
        name="password"
        label={<div className="text-level-3-l">密码</div>}
        className="mb-20"
        rules={[{ required: true, message: '请输入您的登录密码' }]}
      >
        <Input.Password className="px-4 py-3" placeholder="请输入您的登录密码" />
      </Form.Item>
      <Form.Item>
        <Button
          block
          type="primary"
          htmlType="submit"
          className="h-12 px-4 py-3 text-base"
          autoInsertSpace={false}
          loading={loading}
        >
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default LoginForm;
